//基准值计算方法
export function setRem() {
  const baseSize = 13.1 // 和postcss-pxtorem的rootValue保持一致
  const scale = document.documentElement.clientWidth / 192 // 设计稿宽度为375px

  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) - 10 + 'px'
}

// 添加resize事件监听
export function initResponsive() {
  setRem()
  window.addEventListener('resize', setRem)
  window.addEventListener('pageshow', (e) => {
    if (e.persisted) {
      setRem()
    }
  })
}

// 移除事件监听
export function destroyResponsive() {
  window.removeEventListener('resize', setRem)
}

// 设置视口
export function setViewport() {
  const meta = document.createElement('meta')
  meta.name = 'viewport'
  meta.content =
    'width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no'
  document.head.appendChild(meta)
}

// 禁止页面缩放
export function preventZoom() {
  document.addEventListener(
    'touchstart',
    (event) => {
      if (event.touches.length > 1) {
        event.preventDefault()
      }
    },
    { passive: false },
  )

  let lastTouchEnd = 0
  document.addEventListener(
    'touchend',
    (event) => {
      const now = Date.now()
      if (now - lastTouchEnd <= 300) {
        event.preventDefault()
      }
      lastTouchEnd = now
    },
    { passive: false },
  )
}
